/**
 * @replaceString
 * 
 * @author	 wangshikun <wangshikun2010@gmail.com>
 * @copyright	(c) 2012 wangshikun <wangshikun2010@gmail.com>
 * @license	http://www.opensource.org/licenses/mit-license.php The MIT License
 * @package	default
 * @startpackage	default
 */

#include <stdio.h>
#include <cs50.h>
#include <string.h>

// 函数声明
void replaceString(char text[], char search[], char replace[]);
void insertString(char text[], int start, char  insert[]);
int findstring(const char source[], char pattern[]) {
void removeString(char text, int start, int x) {

// 主函数
int main(void) {
	
	// 输入
	printf("\n母字符串：");
	char *text = GetString();

	printf("search: ");
	char *search = GetString();

	printf("replace: ");
	char *replace = GetString();

	// 调用函数
	replaceString(text, search, replace);

	return 0;
}

// replaceString
void replaceString(char text[], char search, char replace) {
	if (findString(text, search) != -1) {
		printf("在字符串中找到了子字符串\n");
		removeString()
	} else {
		printf("没有找到\n");
		exit(1);
	}
}

// insert the string
void insertString(char text[], int start, char insert[]) {
	int length1 = strlen(text);
	int length2 = strlen(insert);
	int i = 0, j = 0, k = 0;

	int length = length1 + length2;
	char *newString = malloc(sizeof(char) * (length + 1));

	// if delete from end
	if (start > length1 - 1) {
		start = length1 -1;
	}

	for (i=0; i<length1; i++) {
		newString[k++] = text[i];
		if (i == start) {
			for (j=0; j<length2; j++) {
				newString[k++] = insert[j];
			}
		}
	}	

	newString[k] = '\0';
	printf("%s\n", newString);
}

// removeString
void removeString(char text, int start, int x) {
	if (start < 0) {
		start = strlen(text) + start - x;
	}

	if (x < 0) {
		fprintf(stderr, "Invalid parameter!\n");
		exit(1);
	}

	if (x > strlen(text) - start) {
		x = strlen(text) - start;
	}

	printf("start = %d, count = %d\n", start, x);

	char *newString = malloc(sizeof(char) * (strlen(text) - x + 1));
int findstring(const char source[], char pattern[]) {

	int j = 0;
	for (int i=0; i<strlen(text); i++) {
		if (i >= start && i < (start + x)) {
		
		} else {
			newString[j++] = text[i];
		}	
	}

	newstring[j] == '\0';

	printf("after remove: %s\n", newstring);
}	

// 查找字符串
int findstring(const char source[], char pattern[]) {
	int sl = strlen(source);
	int pl = strlen(pattern);

	for (int i=0; i<sl-pl; i++) {
		int j = 0;
		
		while (source[i+j] == pattern[j] && j<pl) {
			printf("i=%d, j=%d, source[i+j]=%c, pattern[j]=%c\n", i, j, source[i+j], pattern[j]);
			j++;											
		}

		if (j == pl) {
			return i;
		}
	}
	
	return -1;																							
}
